package com.example.movie.data.user.model

import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.annotation.RequiresApi
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import cn.forward.androids.utils.ThreadUtil
import com.example.movie.R
import com.example.movie.common.constants.LoadingState
import com.example.movie.common.model.RequestResult
import com.example.movie.common.model.Result
import com.example.movie.common.ws.WebSocketClient
import com.example.movie.data.user.model.vo.OrderVo
import com.example.movie.data.user.model.vo.QrOrderLoadingState
import com.example.movie.utils.RequestUtil

class OrderViewModel(val repository: UserRepository) : ViewModel() {

    val addOrderSate = MutableLiveData<RequestResult<Boolean>>()
    val newOrders = MutableLiveData<RequestResult<List<OrderVo>>>()
    val successOrders = MutableLiveData<RequestResult<List<OrderVo>>>()
    val expireOrders = MutableLiveData<RequestResult<List<OrderVo>>>()
    val loadingSate = MutableLiveData<QrOrderLoadingState>()

    private lateinit var webSocketClient: WebSocketClient

    fun addOrder(ids: String, planId: Int) {
        var result: Result<Any>? = null;
        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == LoadingState.OK) {
                    if (result is Result.Success) {
                        addOrderSate.value = RequestResult(
                            success = (result as Result.Success<Boolean>).data
                        )
                    } else {
                        addOrderSate.value = RequestResult(
                            error = R.string.addOrder_fail
                        )
                    }
                }
            }
        }

        ThreadUtil.getInstance().execute {
            result = repository.addOrder(ids, planId)
            val message = Message()
            message.what = LoadingState.OK
            handler.sendMessage(message)
        }

    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun getNewOrder() {
        var result: Result<List<OrderVo>>? = null;
        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == LoadingState.OK) {
                    if (result is Result.Success) {
                        newOrders.value = RequestResult(
                            success = (result as Result.Success<List<OrderVo>>).data
                        )
                    } else {
                        newOrders.value = RequestResult(
                            error = R.string.request_fail
                        )
                    }
                }
            }
        }

        ThreadUtil.getInstance().execute {
            result = repository.newOrder()
            val message = Message()
            message.what = LoadingState.OK
            handler.sendMessage(message)
        }
    }

    /**
     * 使用webSocket接受服务器订单状态
     *
     */
    fun startObserveOrderSate() {
        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == LoadingState.OK) {
                    loadingSate.value = msg.data.getSerializable("state") as QrOrderLoadingState?
                }
            }

        }
        webSocketClient = WebSocketClient(handler)
        //添加请求头认证信息
        webSocketClient.addHeader("Cookie", RequestUtil.getAuthenticationCookie())
        webSocketClient.connect()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun getSuccessOrder() {
        var result: Result<List<OrderVo>>? = null;
        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == LoadingState.OK) {
                    if (result is Result.Success) {
                        successOrders.value = RequestResult(
                            success = (result as Result.Success<List<OrderVo>>).data
                        )
                    } else {
                        successOrders.value = RequestResult(
                            error = R.string.request_fail
                        )
                    }
                }
            }
        }

        ThreadUtil.getInstance().execute {
            result = repository.successOrder()
            val message = Message()
            message.what = LoadingState.OK
            handler.sendMessage(message)
        }

    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun getExpireOrder() {
        var result: Result<List<OrderVo>>? = null;
        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == LoadingState.OK) {
                    if (result is Result.Success) {
                        expireOrders.value = RequestResult(
                            success = (result as Result.Success<List<OrderVo>>).data
                        )
                    } else {
                        expireOrders.value = RequestResult(
                            error = R.string.request_fail
                        )
                    }
                }
            }
        }

        ThreadUtil.getInstance().execute {
            result = repository.expireOrder()
            val message = Message()
            message.what = LoadingState.OK
            handler.sendMessage(message)
        }

    }

    fun stopOrderObserve() {
        webSocketClient.close()
    }

}
